<?php
/**
 * 用户业务类
 * @author solar
 */
class UserService
{
	/**
	 * 检查新浪微博用户是否已授过权，如果没有则创建用户
	 * @author solar
	 * @param int $user_id
	 * @return array
	 */
	public function checkSinaUser($sina_id) {
		$userModel=ModelFactory::get('UserModel');
		$userRow=$userModel->getBySinaID($sina_id);
		if(!$userRow){
			$sinaModel=ModelFactory::get('SinaModel');
			$returnInfo=$sinaModel->get($sina_id);
			if(!$returnInfo) $returnInfo=$sinaModel->createSinaUser($sina_id);
			if($returnInfo===false) return false;
			$u_id=$userModel->createAppUser($sina_id,$returnInfo['screen_name'],$returnInfo['profile_image_url']);
			$sinaModel->setUserID($sina_id,$u_id);
			return array('u_id'=>$u_id,'u_user_name'=>$returnInfo['screen_name'],'sina_id'=>$sina_id);			
		}else return $userRow;
	}
	
	/**
	 * 检查用户是否有加入群组，如果没有则创建一个默认群组
	 * @author solar
	 * @param int $user_id
	 */
	public function checkHasGroup($user_id) {
		$groupNum = ModelFactory::get('GroupUserModel')->countGroup($user_id);
		if($groupNum == 0){
			ServiceFactory::get('GroupService')->createBase('默认群组', $user_id, 1);
		}
	}
	
	/**
	 * 检测是否已登录
	 * @author solar
	 */
	public function isLogined() {
		if(CoreFactory::session()->contains('user_id')) return true;
		else return false;
	}
	
	/**
	 * 登录
	 * @author solar
	 * @param string $username
	 * @param string $password
	 */
	public function login($username,$password) {
		$aField=array('u_name'=>$username,'u_password'=>md5($password));
		$userInfo=ModelFactory::get('UserModel')->getByField($aField);
		if(!$userInfo) return false;
		CoreFactory::session()->set('userInfo',$userInfo);
		return true;
	}
	
	/**
	 * 登出
	 * @author solar
	 */
	public function logout() {
		CoreFactory::session()->destroy();
		return true;
	}
	
	
}